package com.llb666.e.shop.api.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.llb666.e.shop.api.dto.UserLoginDto;
import com.llb666.e.shop.api.dto.UserRegisterDto;
import com.llb666.e.shop.api.vo.UsersVo;
import com.llb666.e.shop.domain.service.UserService;
import com.llb666.e.shop.infracore.web.BaseResponse;
import com.llb666.e.shop.infracore.web.DataResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 斌~
 * @date 2022/8/7 下午9:23
 */

@RestController
@Tag(name = "用户注册登录接口", description = "用户注册登录接口")
@RequestMapping("/passport")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class UsersController {

    private final UserService userService;

    @Operation(summary = "判断用户名称是否存在", description = "判断用户名称是否存在", method = "GET")
    @GetMapping("/usernameIsExist")
    public BaseResponse usernameIsExist(@RequestParam String username) {
        return userService.queryUsernameIsExist(username);
    }

    @Operation(summary = "登录", description = "登录", method = "POST")
    @PostMapping("/login")
    public DataResponse<UsersVo> login(@RequestBody UserLoginDto userDto,
                                       HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {

        return userService.login(UserLoginDto.Converter.INSTANCE.dto2do(userDto),
                request,response);
    }

    @Operation(summary = "注册", description = "注册", method = "POST")
    @PostMapping("/regist")
    public BaseResponse register(@RequestBody UserRegisterDto userDto,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws JsonProcessingException {
        userService.register(userDto,request,response);
        return DataResponse.ok();
    }

    @Operation(summary = "退出登录", description = "退出登录", method = "POST")
    @PostMapping("/logout")
    public BaseResponse logout(@RequestParam String userId, HttpServletRequest request,
                               HttpServletResponse response) {
        return userService.logout(userId,request,response);
    }

}
